<template>
  <el-form ref="form" :model="form" :rules="rules" class="form">
      <template v-if="success">
        <div class="success">
          <div class="success-imgBox">
            <img src="@/assets/images_login/zc_success_pic.png" alt="">
          </div>
          <div class="success-title">注册成功!</div>
          <div class="success-content">您的账号还未认证，<span>请完善企业信息</span> 提交认证即可使用更多平台服务</div>
          <button class="success-btn" @click="goAccredited">去企业认证</button>
        </div>
      </template>
      <template v-else>
        <div class="title">注册您的账户</div>
        <div class="register">
          <span class="content">已有账户？</span>
          <span class="btn imgBox" @click="$emit('shift')">前去登录<img src="@/assets/images_login/dl_point_icon.png" alt="dl_point"></span>
        </div>
      <div class="input">
        <el-form-item prop="username" :error="userNameError">
          <template #error="scoped">
            <span class='error-message'>{{scoped.error}}</span>
          </template>
          <div class="input-box">
            <input
            v-model="form.username"
            type="text"
            placeholder="输入账号"
            autocomplete="new-text">
            <div class="imgBox">
              <img class="input-icon" src="@/assets/images_login/user_icon.png" alt="user_icon">
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="password">
          <template #error="scoped">
            <span class='error-message'>{{scoped.error}}</span>
          </template>
          <div class="input-box">
            <input v-model="form.password" :type="showPassword?'text':'password'"
            placeholder="输入密码(6-20个字符)"
            autocomplete="new-password">
            <div class="imgBox">
              <img class="input-icon" src="@/assets/images_login/pwd_icon.png" alt="pwd_icon">
            </div>
            <div class="imgBox">
              <img class="input-icon-suffix" :src="showPassword?require('@/assets/images_login/xs_icon.png'):require('@/assets/images_login/yc_icon.png')" alt="pwd_icon" @click="showPassword=!showPassword">
            </div>
          </div>
        </el-form-item>

        <el-form-item prop="repeatPassword">
          <template #error="scoped">
            <span class='error-message'>{{scoped.error}}</span>
          </template>
          <div class="input-box">
            <input
              v-model="form.repeatPassword" type="password"
              placeholder="确认密码" autocomplete="new-password"
            >
            <div class="imgBox">
              <img class="input-icon" src="@/assets/images_login/qrpwd_icon.png" alt="pwd_icon">
            </div>
          </div>
        </el-form-item>

      </div>

      <el-form-item prop="code" v-if="captchaOnOff">
        <template #error="scoped">
          <span class='error-message'>{{scoped.error}}</span>
        </template>
        <el-input
          v-model="form.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleRegister"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code imgBox">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>

        <el-button
          :class="{btnClass:fullIn}"
          :loading="loading"
          size="medium"
          type="primary"
          class="formBtn"
          @click.native.prevent="handleRegister"
        >
          <span v-if="!loading">注册</span>
          <span v-else>注册中...</span>
        </el-button>
        <div class="protocol">
          <input  type="checkbox" id="protocol" v-model="protocol">
          <label for="protocol"></label>
          <p class="content">登录即代表您同意 <span @click="dialogVisible=true;articleType=0">平台服务协议</span> 和 <span @click="dialogVisible=true;articleType=1">隐私政策</span></p>
        </div>
      </template>
      <Dialog :visible.sync="dialogVisible" :type="articleType"></Dialog>
  </el-form>
</template>

<script>
import { getCodeImg,shopRegister } from "@/api/login";
import Dialog from './dialog'
export default {
  name:'RegisterForm',
  components:{
    Dialog
  },
  data(){
    return {
      articleType:0,
      dialogVisible:false,
      showPassword:false,
      protocol:false,
      automaticLogIn:true,
      captchaOnOff:false,
      loading:false,
      success:false,
      codeUrl:'',
      userNameError:'',
      form:{
        username:'',
        password:'',
        repeatPassword:'',
        rememberMe:false,
        code:'',
        uuid:''
      },
      rules:{
        username:[{
          required:true,
          trigger:'blur',
          message:'用户名不能为空'
        },{
          pattern:/^\S{5,20}$/,
          trigger:'blur',
          message:'用户名长度必须介于5和20之间'
        }],
        password:[{
          required:true,
          trigger:'blur',
          message:'密码不能为空'
        },{
          // pattern:/^\S*(?=\S{6,20})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/,
          pattern:/^\S{6,20}$/,
          trigger:'blur',
          // message:'密码应包含数字，大小写字母，特殊符号（6-20位）'
          message:'密码应包含6-20位'
        }],
        repeatPassword:[
          {
            required:true,
            trigger:'blur',
            message:'密码重复不能为空'
          },{
            validator:(rule,value,callback)=>{
              if(this.form.password !== value){
                callback(new Error("两次输入的密码不一致"))
              }else{
                callback()
              }
            }
          }
        ],
        code:{
          required:true,
          trigger:'change',
          message:'请输入验证码'
        }
      }
    }
  },
  computed:{
    fullIn(){
      return Boolean(this.form.username && this.form.password && this.form.repeatPassword && this.protocol)
    }
  },
  created(){
    this.getCode()
  },
  methods:{
    hidePasswordEvent(){
      this.showPassword = false
    },
    goAccredited(){
      window.location.href =  window.location.href
      // this.handleLogin()
      // this.$router.push({
      //   path:"/approve"
      // })
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.form.uuid = res.uuid;
        }
      });
    },
    handleLogin() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if(!this.protocol){
            return this.$modal.msgWarning('请先阅读协议')
          }
          this.loading = true;
          //密码明文传输

          this.$store.dispatch("Login", this.form).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          }).catch((e) => {
            this.usernameError = '用户名或密码错误'
            this.loading = false;
            if (this.captchaOnOff) {
              this.getCode();
            }
          });

        }
      });
    },
    handleRegister(){
      this.$refs.form.validate(valid=>{
        if(valid){
          if(!this.protocol){
            return this.$modal.msgWarning('请阅读协议')
          }
          this.loading = true;
          this.$modal.confirm('是否确认注册平台账户？').then(()=>{

            shopRegister(this.form).then(res=>{
              sessionStorage.setItem('username', this.form.username)
              sessionStorage.setItem('password', this.form.password)
              sessionStorage.setItem('autologin', this.automaticLogIn)
              this.$modal.msgSuccess('注册成功')
              this.success = true
            }).catch(err=>{
              this.userNameError = err.message
              // this.$modal.msgError('注册失败')
            }).finally(()=>{
              this.loading = false
            })
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.btnClass{
  background-color:#c19765!important;
}
</style>
